package br.ucb.ProjetoFinal.validators;

import br.ucb.ProjetoFinal.bean.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 * source : www.javabeat.net
 */
public class ValidatorData implements Validator{

    public void validate(FacesContext facesContext, UIComponent arg1, Object value) throws ValidatorException {

        String data = (String) value;
        String campo = (String) arg1.getAttributes().get("numCampo"); ;

        Pattern mascara = Pattern.compile("[0-9]{2}/[0-9]{2}/[0-9]{4}");
        Matcher match = mascara.matcher(data);

        if(!data.equals("")){ //JSF cuida das datas nulas
            if (!match.matches()){
                FacesMessage message = new FacesMessage();
                message.setSummary("Data "+campo+"  - Data inválida. Ela deveria estar no formato 'dd/mm/aaaa'");
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(message);                   
            }
            else{
                if(!validaData(data)){
                    FacesMessage message = new FacesMessage();
                    message.setSummary("Data "+campo+"  - Data inválida.");
                    message.setSeverity(FacesMessage.SEVERITY_ERROR);
                    throw new ValidatorException(message);                           
                }
            }
        }

    }

    public boolean validaData(String data){
        try{
            DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
            df.setLenient(false);
            df.parse(data);

        }
        catch (Exception e){return false;}

        return true;
    }

}